""" Scripts """
import pprint
import os
import sys
import django
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tuntun.settings'
django.setup()

from django.db import transaction
from apps.repo.models import *
from apps.product.models import *
import json

from common import int_2_2d

def batch_make_repo_store_units():
    repos = [
        {
            "name": "云南仓",
            "no": "KM",
            "address": "昆明天池",
            "price_per_100g_1d": "250.00",
            "store_units": [
                [str(i) for i in range(5)],
                [chr(i) for i in list(range(65, 70))],
                ['a', 'b'],
                [int_2_2d(i) for i in range(1, 10)],
                ['a', 'b'],
                ['01', '02', '03', '04',],
                ['a', 'b'],
                {
                    "a": ["01", '02'],
                    "b": ['01', '02', '03', '04',],
                }
            ]
        }
    ]
    with transaction.atomic():
        for repo in repos:
            name = repo['name']
            no = repo['no']
            address = repo['address']
            price_per_100g_1d = repo['price_per_100g_1d']
            robj = Repo(name=name, address=address, no=no, price_per_100g_1d=price_per_100g_1d)
            store_units = repo['store_units']
            sus = []
            for store_type in store_units[2]:
                if store_type == 'a':
                    parent_type = 'CROWD_BOX_V1'
                else:
                    parent_type = 'CHEST_V1'
                f0 = store_units[0]
                f1 = store_units[1]
                # f2 = [store_type],
                f3 = store_units[3]
                f4 = store_units[4]
                f5 = store_units[5]
                f6 = store_units[6]
                f7 = store_units[7][store_type]
                # print(len(f0), len(f1), store_type, len(f3), len(f4), len(f5), len(f6), len(f7))
                i = 0
                for a in f0:
                    for b in f1:
                        # for c in f2:
                        for d in f3:
                            for e in f4:
                                for f in f5:
                                    for g in f6:
                                        for h in f7:
                                            fields = [a, b, store_type, d, e, f, g]
                                            repo_no = robj.no+''.join(fields)+h
                                            store_unit = StoreUnit(
                                                repo=robj,
                                                no=h,
                                                parent_type=parent_type,
                                                fields=fields,
                                                repo_no=repo_no
                                            )
                                            sus.append(store_unit)
                                            print(i, store_unit)
                                            i += 1
                                            # if i > 500:
                                            #     break
            robj.save()
            StoreUnit.objects.bulk_create(sus)


def batch_make_unique_codes():
    stores = [
        {
            "store_type": "BRAND",
            "store_name": "品牌茶庄",
            "store_desc": "-",
            "mountain_desc": "-",
            "mountain_history": "-",
            "maker_and_tech_desc": "-",
            "repo_desc": "-",
            "brands": [
                {
                    ""
                }
            ]
        }
    ]

def get_user_input(prompt, choices):
    while True:
        print('---------')
        for id, desc in choices:
            print(id, desc)
        value = input(prompt+': ').strip()
        if value:
            break
    return value

class ProductInRepo(object):
    def __init__(self):
        product_id = get_user_input("输入产品ID", Product.make_choices())
        unique_code_version = get_user_input("输入唯一码版本号", GoodsBlock.UniqueCodeVersion.get_choices())
        repo_id = get_user_input("输入仓库ID", Repo.make_choices())
        # store_unit_id = get_user_input("输入存储单元", StoreUnit.make_choices_by_page(offset=0, limit=10, repo_id=repo_id, in_use=False))
        trade_type = get_user_input("交易类型", choices=GoodsBlock.TradeType.get_choices())
        no = get_user_input("输入茶饼号", choices=())

        product = Product.objects.get(pk=product_id)
        fields = product.get_unique_code()
        unique_code = ''.join(fields) + no

        print(product, unique_code, unique_code_version, repo_id, trade_type, no, fields)
        if '-' in no:
            start = int(no.split('-')[0].strip())
            end = int(no.split('-')[1].strip())
            for i in range(start, end):
                tea_no = 'AA' + int_2_2d(i)
                self.goods_block_in_repo(product, unique_code, unique_code_version, repo_id, trade_type, tea_no, fields)
        else:
            self.goods_block_in_repo(product, unique_code, unique_code_version, repo_id, trade_type, no, fields)

    def goods_block_in_repo(self, product_obj, unique_code, unique_code_version, repo_id, trade_type, no, fields):
        store_unit = StoreUnit.objects.filter(in_use=False).first()
        gb = GoodsBlock()
        gb.product = product_obj
        gb.unique_code = unique_code
        gb.unique_code_version = unique_code_version
        gb.repo_id = repo_id
        gb.store_unit_id = store_unit.id
        gb.trade_type = trade_type
        gb.no = no
        gb.fields = fields
        gb.save()
        #
        store_unit.in_use = True
        store_unit.save()

# def walk_aa(aa):
#     print(aa)
#     if aa['code'] is None:
#         aa['code'] = 'EMPTY'
#     if aa['parent'] is None:
#         parent_obj = AdministrativeArea.objects.create(nid=aa['nid'], level=aa['level'], name=aa['name'], zip_code=aa['code'], parent=aa['parent'])
#     else:
#         parent_obj = AdministrativeArea.objects.create(nid=aa['nid'], level=aa['level'], name=aa['name'], zip_code=aa['code'], parent=AdministrativeArea.objects.get(nid=aa['parent']))
#     if not aa['children']:
#         return
#     else:
#         for child_aa in aa['children']:
#             walk_aa(child_aa)

# def import_aas():
#     file = '/Users/roc.maple/Documents/Resources/hro_common.json'
#     tree_file = '/Users/roc.maple/Documents/Resources/china_aa_tree.json'
#     data = json.load(open(file))
#     aa_rows = []
#     aa_rows_map = {}
#     root = {'children': []}
#     ps = []
#     cs = []
#     xs = []
#     for d in data:
#         # print(d['model'])
#         if d['model'] == 'common.administrativearea':
#             aa_rows.append(d)
#             aa_rows_map[d['pk']] = d['fields']
#             if d['fields']['parent'] is None:
#                 root.update(d['fields'])
#                 root['nid'] = d['pk']
#             if d['fields']['level'] == 'P':
#                 tmp = d['fields']
#                 tmp['nid'] = d['pk']
#                 tmp['children'] = []
#                 ps.append(tmp)
#             if d['fields']['level'] == 'C':
#                 tmp = d['fields']
#                 tmp['nid'] = d['pk']
#                 tmp['children'] = []
#                 cs.append(tmp)
#             if d['fields']['level'] == 'X':
#                 tmp = d['fields']
#                 tmp['nid'] = d['pk']
#                 tmp['children'] = []
#                 xs.append(tmp)
#     # pprint.pprint(aa_rows_map, indent=2)
#     # print(len(ps), len(cs), len(xs))
#
#     for pi in range(len(ps)):
#         for ci in range(len(cs)):
#             for xi in range(len(xs)):
#                 if xs[xi]['parent'] == cs[ci]['nid']:
#                     cs[ci]['children'].append(xs[xi])
#             if cs[ci]['parent'] == ps[pi]['nid']:
#                 ps[pi]['children'].append(cs[ci])
#     root['children'] = ps
#
#     with transaction.atomic():
#         walk_aa(root)
#         # root_obj = AdministrativeArea.objects.create(nid=root['nid'], level=root['level'], name=root['name'], zip_code=root['code'], parent=None)

if __name__ == '__main__':
    # batch_make_repo_store_units()
    pm = ProductInRepo()
    # import_aas()
